package com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.repository.HddcRelocationiscatalogNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.repository.HddcRelocationiscatalogRepository;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.repository.entity.HddcRelocationiscatalogEntity;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.service.HddcRelocationiscatalogService;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.viewobjects.HddcRelocationiscatalogPageVO;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.viewobjects.HddcRelocationiscatalogQueryParams;
import com.css.zfzx.sjcj.modules.hddcRelocationISCatalog.viewobjects.HddcRelocationiscatalogVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-28
 */
@Service
public class HddcRelocationiscatalogServiceImpl implements HddcRelocationiscatalogService {

    private final HddcRelocationiscatalogRepository hddcRelocationiscatalogRepository;
    private final HddcRelocationiscatalogNativeRepository hddcRelocationiscatalogNativeRepository;
    private final RelocationCatalogsPointExcelImportVerifyHandler relocationCatelogPointExcelImportVerifyHandler;

    @Autowired
    public HddcRelocationiscatalogServiceImpl(HddcRelocationiscatalogRepository hddcRelocationiscatalogRepository,
                                              HddcRelocationiscatalogNativeRepository hddcRelocationiscatalogNativeRepository,
                                              RelocationCatalogsPointExcelImportVerifyHandler relocationCatelogPointExcelImportVerifyHandler) {
        this.hddcRelocationiscatalogRepository = hddcRelocationiscatalogRepository;
        this.hddcRelocationiscatalogNativeRepository = hddcRelocationiscatalogNativeRepository;
        this.relocationCatelogPointExcelImportVerifyHandler = relocationCatelogPointExcelImportVerifyHandler;
    }

    @Override
    public JSONObject queryHddcRelocationiscatalogs(HddcRelocationiscatalogQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcRelocationiscatalogPageVO> hddcRelocationiscatalogPage = this.hddcRelocationiscatalogNativeRepository.queryHddcRelocationiscatalogs(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcRelocationiscatalogPage);
    }


    @Override
    public HddcRelocationiscatalogEntity getHddcRelocationiscatalog(String id) {
        return this.hddcRelocationiscatalogRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRelocationiscatalogEntity saveHddcRelocationiscatalog(HddcRelocationiscatalogEntity hddcRelocationiscatalog) {
        String uuid = UUIDGenerator.getUUID();
        hddcRelocationiscatalog.setUuid(uuid);
        hddcRelocationiscatalog.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcRelocationiscatalog.setCreateTime(now);
        hddcRelocationiscatalog.setUpdateTime(now);
        hddcRelocationiscatalog.setIsValid(PlatformConstants.Y);
        hddcRelocationiscatalog.setQualityinspectionStatus(PlatformConstants.N);
        hddcRelocationiscatalog.setExtends10(PlatformConstants.Y);
        this.hddcRelocationiscatalogRepository.save(hddcRelocationiscatalog);
        return hddcRelocationiscatalog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRelocationiscatalogEntity updateHddcRelocationiscatalog(HddcRelocationiscatalogEntity hddcRelocationiscatalog) {
        HddcRelocationiscatalogEntity entity = hddcRelocationiscatalogRepository.findById(hddcRelocationiscatalog.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcRelocationiscatalog);
        hddcRelocationiscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRelocationiscatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRelocationiscatalogRepository.save(hddcRelocationiscatalog);
        return hddcRelocationiscatalog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRelocationiscatalogs(List<String> ids) {
        List<HddcRelocationiscatalogEntity> hddcRelocationiscatalogList = this.hddcRelocationiscatalogRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcRelocationiscatalogList) && hddcRelocationiscatalogList.size() > 0) {
            for (HddcRelocationiscatalogEntity hddcRelocationiscatalog : hddcRelocationiscatalogList) {
                hddcRelocationiscatalog.setIsValid(PlatformConstants.N);
                hddcRelocationiscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRelocationiscatalog.setUpdateTime(new Date());
                this.hddcRelocationiscatalogRepository.save(hddcRelocationiscatalog);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcRelocationiscatalogQueryParams queryParams, HttpServletResponse response) {
        List<HddcRelocationiscatalogEntity> yhDisasterEntities = hddcRelocationiscatalogNativeRepository.exportYhDisasters(queryParams);
        List<HddcRelocationiscatalogVO> list = new ArrayList<>();
        for (HddcRelocationiscatalogEntity entity : yhDisasterEntities) {
            HddcRelocationiscatalogVO yhDisasterVO = new HddcRelocationiscatalogVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "小震重新定位目录-点", "小震重新定位目录-点",
                HddcRelocationiscatalogVO.class, "小震重新定位目录-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(relocationCatelogPointExcelImportVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcRelocationiscatalogVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRelocationiscatalogVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcRelocationiscatalogVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcRelocationiscatalogVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcRelocationiscatalogVO> list) {
        HddcRelocationiscatalogEntity yhDisasterEntity;
        for (HddcRelocationiscatalogVO hddcRelocationiscatalogVO : list) {
            yhDisasterEntity = new HddcRelocationiscatalogEntity();
            BeanUtils.copyProperties(hddcRelocationiscatalogVO, yhDisasterEntity);
            saveHddcRelocationiscatalog(yhDisasterEntity);
        }
    }

    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcRelocationiscatalogEntity> hddcRelocationiscatalogList = this.hddcRelocationiscatalogRepository.queryHddcRelocationiscatalogsByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcRelocationiscatalogList) && hddcRelocationiscatalogList.size() > 0) {
            for (HddcRelocationiscatalogEntity hddcRelocationiscatalog : hddcRelocationiscatalogList) {
                hddcRelocationiscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRelocationiscatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRelocationiscatalog.setIsValid("0");
                this.hddcRelocationiscatalogRepository.save(hddcRelocationiscatalog);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcRelocationiscatalogEntity> hddcRelocationiscatalogList = this.hddcRelocationiscatalogRepository.queryHddcRelocationiscatalogsByTaskId(taskIds);
        if (!PlatformObjectUtils.isEmpty(hddcRelocationiscatalogList) && hddcRelocationiscatalogList.size() > 0) {
            for (HddcRelocationiscatalogEntity hddcRelocationiscatalog : hddcRelocationiscatalogList) {
                hddcRelocationiscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRelocationiscatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRelocationiscatalog.setIsValid("0");
                this.hddcRelocationiscatalogRepository.save(hddcRelocationiscatalog);
            }
        }
    }

}
